package com.dong.aoptools.util;

import com.dong.aoptools.Application;
import com.dong.aoptools.Position_Class__;

import java.io.File;
import java.net.URL;

/**
 * @description: 路径工具类
 * @author: 陈瑞东
 * @create: 2021-11-16 17:07
 */
public class PathUtils {

    /**
     * 路径 / 转 .
     * @param path 路径
     * @return 转换后的路径
     */
    public static String slash2Point(String path) {
        return path.replaceAll("/", ".");
    }

    /**
     * 路径 . 转 /
     * @param path 路径
     * @return 转换后的路径
     */
    public static String point2Slash(String path) {
        return path.replaceAll("\\.", "/");
    }

    /**
     * 获取jar包的目录路径
     * @return
     */
    public static String getRootPath() {
        File file = getJarFile();
        return file.getParentFile().getAbsolutePath();
    }

    /**
     * 获取jar包的目录路径
     * @return
     */
    public static String getJarPath() {
        File file = getJarFile();
        return file.getAbsolutePath();
    }

    /**
     * 获取jar包文件对象
     * @return
     */
    private static File getJarFile() {
        //        URL resource = PathUtils.class.getClassLoader().getResource(PropertiesConst.CONFIG_DIR);
        URL resource = Position_Class__.class.getResource("Position_Class__.class");
        // file:/F:/download/aop/aoptools-1.0-SNAPSHOT.jar!/config.properties
        String path = resource.getPath();

        // 去掉类路径
        String className = point2Slash(Application.class.getName());
        int index = path.lastIndexOf(className);
        if (index != -1) {
            path = path.substring(0, index) + "config";
        }
        // 去掉开头的 file:
        if (path.startsWith("file:")) {
            path = path.substring("file:".length());
        }
        // 去掉结尾的 !
        if (path.indexOf("!") != -1) {
            path = path.substring(0, path.indexOf("!"));
        }

        File file = new File(path);
        return file;
    }
}
